package com.decent.manager.task.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.decent.common.entity.http.ChengQuanCode;
import com.decent.common.entity.http.ParamNode;
import com.decent.common.entity.http.ResultMessage;
import com.decent.common.util.http.ChengHttpUtils;
import com.decent.manager.config.chengquan.ChengQuanConfig;
import com.decent.manager.system.dao.SystemGoodsDao;
import com.decent.manager.system.vo.SystemGoodsVO;
import com.decent.common.entity.http.StockEntity;
import com.decent.manager.task.service.GoodsStockTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: decent Gjh
 * @date: 2022/10/29/10:01
 * @description:
 */
@Service
@Slf4j
public class GoodsStockTaskServiceImpl implements GoodsStockTaskService {
    private final ChengQuanConfig config;
    private final SystemGoodsDao goodsDao;

    public GoodsStockTaskServiceImpl(ChengQuanConfig config, SystemGoodsDao goodsDao) {
        this.config = config;
        this.goodsDao = goodsDao;
    }

    /**
     * 商品库存同步
     */
    @Override
    public void goodsStockSynchronized(){
        List<SystemGoodsVO> systemGoods = goodsDao.selectGoods(null);
        for (SystemGoodsVO systemGood : systemGoods) {
            try {
                List<ParamNode<String, Object>> params = new ArrayList<>();
                params.add(new ParamNode<>("goods_no", systemGood.getCode()));
                params.add(new ParamNode<>("timestamp", System.currentTimeMillis() + ""));
                params.add(new ParamNode<>("app_id", config.getAppid()));
                String jsonResult = ChengHttpUtils.getUrl("/coupon/goods/stock", params, config.getKey());
                ResultMessage<StockEntity> result = JSON.parseObject(jsonResult,
                        new TypeReference<ResultMessage<StockEntity>>(StockEntity.class) {
                        });
                if (result.getCode() == ChengQuanCode.SUCCESS.getCode()) {
                    int row = goodsDao.updateStockNumByCode(result.getData().getGoodsNo(), result.getData().getStockNum());
                    if (row == 0) {
                        log.error("库存更新失败：code = "+ result.getData().getGoodsNo());
                    }else {
                        systemGood.setSuccess(true);
                    }
                }else {
                    log.error("更新库存时请求橙券时发生错误 code:"+result.getCode()+" 商品code = "+ result.getData().getGoodsNo());
                }
            }catch (Exception e) {
                log.error("更新库存时发生错误:"+e.getMessage());
            }
        }
        long count = systemGoods.stream().filter(o -> o.getSuccess() != null && o.getSuccess()).count();
        log.info("定时更新库存完成   成功:"+ count+"   失败:"+(systemGoods.size()-count));
    }

}
